package com.squirrel.michale;

import java.util.HashMap;
import java.util.List;
import java.util.Map;
import java.util.stream.Collectors;

/**
 * @author guanhao 观浩
 * @version 1.0.0.0
 * @createTime 2023/2/2 9:06 PM
 * @company Michale Squirrel
 * @link
 * @description
 */
public class Exam_iLearning20220610 {

    class BikeManager {


    private final Map<Integer, Integer> countMap = new HashMap<>();

    private final Map<Integer, Integer> parentMap = new HashMap<>();

    private final int capacity;

 

    /**

     * 初始化

     *

     * @param preNode 父节点数组

     * @param capacity 租借点容量

     */

    public BikeManager(int[] preNode, int capacity) {

        this.capacity = capacity;

        for (int i = 1; i < preNode.length; i++) {

            parentMap.put(i, preNode[i]);

            countMap.put(i, capacity / 2);

        }

    }

 

    /**

     * 借车

     *

     * @param nodeId 租借点id

     * @param num 借车数量

     * @return 剩余数量

     */

    public int rentBikes(int nodeId, int num) {

        if (!countMap.containsKey(nodeId)) {

            return 0;

        }

        if (countMap.get(nodeId) < num) {

            rentBikes(parentMap.get(nodeId), num - countMap.get(nodeId));

            countMap.put(nodeId, 0);

            return 0;

        }

        countMap.put(nodeId, countMap.get(nodeId) - num);

        return countMap.get(nodeId);

    }

 

    /**

     * 还车

     *

     * @param nodeId 租借点id

     * @param num 还车数量

     * @return 剩余数量

     */

    public int returnBikes(int nodeId, int num) {

        if (!countMap.containsKey(nodeId)) {

            return 0;

        }

        int remain = countMap.get(nodeId) + num - capacity;

        if (remain > 0) {

            returnBikes(parentMap.get(nodeId), remain);

            countMap.put(nodeId, capacity);

            return capacity;

        }

        countMap.put(nodeId, countMap.get(nodeId) + num);

        return countMap.get(nodeId);

    }

 

    /**

     * 重置

     *

     * @return 重置节点的数量

     */

    public int reset() {

        int result = 0;

        for (Map.Entry<Integer, Integer> node : countMap.entrySet()) {

            if (node.getValue() == 0 || node.getValue() == capacity) {

                countMap.put(node.getKey(), capacity / 2);

                ++result;

            }

        }

        return result;

    }

 

    /**

     * 返回top5的节点id

     * 

     * @return top5的节点id

     */

    public int[] getTop5Nodes() {

        final List<Integer> list = countMap.entrySet().stream()

                .sorted((n1, n2) -> n1.getValue().equals(n2.getValue()) ? n1.getKey() - n2.getKey() : n2.getValue() - n1.getValue())

                .map(Map.Entry::getKey).limit(5).collect(Collectors.toList());

        int[] result = new int[list.size()];

        for (int i = 0; i < list.size(); i++) {

            result[i] = list.get(i);

        }

        return result;

    }

}
}
